<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Cache;
use think\cache\driver\Redis;

/**
 * 学生接口
 */
class Student extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiTitle    (学生排行榜)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/9 13:57)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/student/ranking)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function ranking()
    {
        $list_rows = $this->request->request('list_rows', 10);

        $results = \app\admin\model\Student::alias('a')
            ->join('__BASE_CLASSES__ b', 'b.id = a.class_id', 'left')
            ->join('__BASE_FACULTY__ c', 'c.id = a.faculty_id', 'left')
            ->field('a.id,a.name,a.score,b.grade_name,b.name class_name,c.name faculty_name')
            ->order('score', 'desc')
            ->paginate($list_rows);

        if ($results) {
            if (!is_array($results)) $results = $results->toArray();

            if (isset($results['data'])) {

                // 第一个是分数最大的
                $max = current($results['data']);

                // 获取比当前最大分分数高的人数
                $count = \app\admin\model\Student::where('score', '>', $max['score'])->count();

                foreach ($results['data'] as $key => $value) {

                    //数组中第一个是当前分数最高的
                    if ($key == 0) {
                        $results['data'][$key]['sort'] = $count + $key + 1;
                    } else {
                        // 继续循环
                        // 如果当前的分数与上一个的相等 那么就与上一个的排名并列
                        if ($results['data'][$key - 1]['score'] == $value['score']) {
                            $results['data'][$key]['sort'] = $results['data'][$key - 1]['sort'];
                        } else {
                            // 如果不等 那就看看有没有分页情况
                            // 如果有分页 也就是说之前的所有的分数都大于当前的分数 排名累加上
                            $results['data'][$key]['sort'] = ($results['current_page'] - 1) * $list_rows + $key + 1;
                        }
                    }
                }
            }
        }

        $this->success('', $results);
    }

    /**
     * @ApiTitle    (我的排行)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/9/2 10:28)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/student/myRanking)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1567392702",
    "data": {
    "sort": 1
    }
    })
     */
    public function myRanking()
    {
        if (\app\common\model\User::STUDENT == $this->auth->target_type) {

            $student = \app\admin\model\Student::alias('a')
                ->join('__BASE_CLASSES__ b', 'b.id = a.class_id', 'left')
                ->join('__BASE_FACULTY__ c', 'c.id = a.faculty_id', 'left')
                ->field('a.id,a.name,a.score,b.grade_name,b.name class_name,c.name faculty_name')
                ->where('a.id', $this->auth->target_id)->find();

            if (!$student) $this->success('', null);

            $count = \app\admin\model\Student::where('score', '>', $student['score'])->count();

            $this->success('', [
                'sort'          => $count + 1,
                'name'          => $student['name'],
                'score'         => $student['score'],
                'grade_name'    => $student['grade_name'],
                'class_name'    => $student['class_name'],
                'faculty_name'  => $student['faculty_name'],
            ]);
        }

        $this->success('', null);
    }

    /*public function test()
    {
        $redis = Cache::store('redis');

        $redis->zAdd('dorm_ranking', 1, 'zhangsan');
        $redis->zAdd('dorm_ranking', 2, 'lisi');
        $redis->zAdd('dorm_ranking', 2, 'wanger');

        $redis->zIncrBy('dorm_ranking', 3, 'zhangsan');
        $result = $redis->zRevRange('dorm_ranking', 0, -1, true);

        dd($result);
    }*/
}
